import { Prefab, resources } from "cc"
import BaseSingleClass from "../base/BaseSingleClass"
import { getPrefabPathByName, PrefabInfo } from "../Const"
import PoolHelper from "./PoolHelper"

export default class PrefabHelper extends BaseSingleClass{
    /*private prefabNames=[
        {name:'Radio',path:'prefab/Radio'},
        {name:'DebugDialog',path:'prefab/pop/DebugDialog'}
    ]*/
    /** 所有prefab */
    private prefabMap:Map<string,Prefab>=new Map<string,Prefab>()
    preload(data:PrefabInfo[]):void{
        console.log('prefab加载开始')

        let i=0
        const load=(prefabInfo:PrefabInfo)=>{
            if(this.prefabMap.has(prefabInfo.name)){
                next()
            }else{
                resources.load(prefabInfo.path, Prefab, (err, asset)=>{
                    if (err) {
                        console.error(err);
                        next()
                        return;
                    }
                    //assetManager.releaseAsset(asset);
                    this.prefabMap.set(prefabInfo.name,asset);
                    next()
                });
            }
        }
        const next=()=>{
            i++;
            if(i<data.length){
                load(data[i])
            }else{
                console.log('prefab加载完成')
            }
        }
        load(data[i])
    }
    /**
     * 获取prefab
     * @param name 
     * @returns 
     */
    getPrefab(name:string):Prefab{
        return this.prefabMap.get(name)
    }
    /**
     * 异步方式获取prefab
     * @param name 
     * @returns 
     */
    getPrefabAsync(name:string):Promise<Prefab>{
        return new Promise<Prefab>((resolve,reject)=>{
            if(this.prefabMap.has(name)){
                resolve(this.prefabMap.get(name))
                return
            }
            resources.load(getPrefabPathByName(name), Prefab, (err, asset)=>{
                if (err) {
                    console.error(err);
                    reject(err)
                    return;
                }
                this.prefabMap.set(name,asset);
                resolve(asset)
            });
        })
    }
    trace(){
        const map=this.prefabMap
        for(let [key,value] of map){
            const pool=PoolHelper.getInstance().getPool(value)
            console.log(key,pool.size())
        }
    }
}